package web.add;

import com.fasterxml.jackson.databind.ObjectMapper;
import domain.Chapter;
import domain.Word;
import service.BookService;
import service.WordService;
import service.impl.BookServiceImpl;
import service.impl.WordServiceImpl;
import util.OtherUtil;
import util.ServletUtil;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.*;

@WebServlet("/addBookWord")
public class AddBookWordServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        Map<String,Object> msg = new HashMap<>(8);
        ObjectMapper om = new ObjectMapper();
        String bid = request.getParameter("bid");
        String content = request.getParameter("content");
        String name = request.getParameter("name");
        System.out.println(bid+":"+content+":"+name);
        //某一参数不存在
        if(bid==null||"".equals(bid) || content==null||"".equals(content) || name==null||"".equals(name)){
            msg.put("msg","参数错误");
            msg.put("isSuccess",false);
            om.writeValue(response.getOutputStream(),msg);
        }
        //查询当前书的词频
        WordService  ws = new WordServiceImpl();
        assert bid != null;
        Map<String, Integer> frequencyMap =ws.getWordCollect(Integer.parseInt(bid));

        //获取单词词频
        OtherUtil.getWordFrequency(content, frequencyMap);
        System.out.println(frequencyMap);
        BookService bs = new BookServiceImpl();
        //MAP类转化为单词实例化列表
        List<Word> wordList =new ArrayList<>();
        for(String key:frequencyMap.keySet()){
            wordList.add(new Word(key,Integer.parseInt(bid) ,frequencyMap.get(key)));
        }
        //删除原来数据并添加到数据库添加该章节到数据库
//        int cid, int bid, String name, String content, Date updatedTime
        bs.addChapter(new Chapter(-1,Integer.parseInt(bid),name,content,new Date()));
        bs.delBookWord(Integer.parseInt(bid));
        bs.addBookWord(wordList);
        msg.put("msg","成功");
        msg.put("isSuccess",true);
        om.writeValue(response.getOutputStream(),msg);
    }
}
